<template>
  <div v-if="ModeVisible">

    <ReDialog :width="700" :height="550" :models="ModeVisible" @Closes="CloseModeVisible(RefMoelform)">
      <template #header>
        <h2 style="text-align: center;">新建个人评分模型</h2>
      </template>
      <template #main>
        <p class="zhushi"><span style="color: red;">注</span>:选项中带有*号的为必选项!</p>
        <div class="ModeVisible">
          <el-form :model="Moelform" label-width="120px" ref="RefMoelform">
            <el-form-item label="模型名称" prop="modeName" :rules="[
              {
                required: true,
                message: '请输入评分模型名称',
                trigger: 'blur',
              }]">
              <el-input v-model.trim="Moelform.modeName" maxlength="32" style="width: 370px;" />
            </el-form-item>
            <br>
            <!-- 需要添加的 -->
            <!-- 身份特质 -->
            <TransitionGroup name="fade">
              <el-form-item label="身份特质" v-for="(m, i) in Moelform.IdentityTrait" :key="m.key"
                :prop="Moelform.IdentityTrait">
                <div class="modeForm">
                  <div class="el_sel_btn">
                    <ModeSelect v-model="m['IdentityTrait']" :ModeData="IdentityTrait" :ModeIsDisabled="m.IsDisabled" />
                    &emsp;&emsp;
                    <el-tooltip v-if="!m.IsDisabled" effect="dark" content="添加" placement="top">
                      <el-button @click="handleSelection(m, Number(m.key + 1), 'IdentityTrait', IdentityTrait)" link
                        class="tran45" type="primary" :icon="useRenderIcon(CloseBold)" /></el-tooltip>
                    <el-tooltip effect="dark" content="删除" placement="top" v-else>
                      <el-button @click="deleteFormValue(m, m.key, 'IdentityTrait', IdentityTrait)" link type="danger"
                        :icon="useRenderIcon(CloseBold)" />
                    </el-tooltip>
                  </div>
                  <div class="show_view">
                    <div class="show_view_list show_left_bor1">
                      <p class="view_list1">{{ m['IdentityTrait']?.lableOne?.label }}</p>
                      <p class="view_list2">{{ m['IdentityTrait']?.lableTow?.label }}</p>
                      <div class="show_view_lists">
                        <dl v-for="(ll, ii) in m?.IdentityTrait?.lableTow?.children" :key="ii">
                          <dd>{{ ll.text }}</dd>
                          <dd><span>{{ ll.score }}分</span></dd>
                        </dl>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <!-- 行为特质 -->
              <el-form-item label="行为特质" v-for="(m, i) in Moelform.BehavioralTrait" :key="m.key"
                :prop="Moelform.BehavioralTrait">
                <div class="modeForm">
                  <div class="el_sel_btn">
                    <ModeSelect v-model="m['BehavioralTrait']" :ModeData="BehavioralTrait"
                      :ModeIsDisabled="m.IsDisabled" />
                    &emsp;&emsp;
                    <el-tooltip v-if="!m.IsDisabled" effect="dark" content="添加" placement="top">
                      <el-button @click="handleSelection(m, Number(m.key + 1), 'BehavioralTrait', BehavioralTrait)" link
                        class="tran45" type="primary" :icon="useRenderIcon(CloseBold)" /></el-tooltip>
                    <el-tooltip effect="dark" content="删除" placement="top" v-else>
                      <el-button @click="deleteFormValue(m, m.key, 'BehavioralTrait', BehavioralTrait)" link type="danger"
                        :icon="useRenderIcon(CloseBold)" />
                    </el-tooltip>
                  </div>
                  <div class="show_view">
                    <div class="show_view_list show_left_bor2">
                      <p class="view_list1">{{ m['BehavioralTrait']?.lableOne?.label }}</p>
                      <p class="view_list2">{{ m['BehavioralTrait']?.lableTow?.label }}</p>
                      <div class="show_view_lists">
                        <dl v-for="(ll, ii) in m?.BehavioralTrait?.lableTow?.children" :key="ii">
                          <dd>{{ ll.text }}</dd>
                          <dd><span>{{ ll.score }}分</span></dd>
                        </dl>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <!-- 履约能力 -->
              <el-form-item label="履约能力" v-for="(m, i) in Moelform.CapacityPerform" :key="m.key"
                :prop="Moelform.CapacityPerform">
                <div class="modeForm">
                  <div class="el_sel_btn">
                    <ModeSelect v-model="m['CapacityPerform']" :ModeData="CapacityPerform"
                      :ModeIsDisabled="m.IsDisabled" />
                    &emsp;&emsp;
                    <el-tooltip v-if="!m.IsDisabled" effect="dark" content="添加" placement="top">
                      <el-button @click="handleSelection(m, Number(m.key + 1), 'CapacityPerform', CapacityPerform)" link
                        class="tran45" type="primary" :icon="useRenderIcon(CloseBold)" /></el-tooltip>
                    <el-tooltip effect="dark" content="删除" placement="top" v-else>
                      <el-button @click="deleteFormValue(m, m.key, 'CapacityPerform', CapacityPerform)" link type="danger"
                        :icon="useRenderIcon(CloseBold)" />
                    </el-tooltip>
                  </div>
                  <div class="show_view">
                    <div class="show_view_list show_left_bor3">
                      <p class="view_list1">{{ m['CapacityPerform']?.lableOne?.label }}</p>
                      <p class="view_list2">{{ m['CapacityPerform']?.lableTow?.label }}</p>
                      <div class="show_view_lists">
                        <dl v-for="(ll, ii) in m?.CapacityPerform?.lableTow?.children" :key="ii">
                          <dd>{{ ll.text }}</dd>
                          <dd><span>{{ ll.score }}分</span></dd>
                        </dl>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <!-- 信用历史 -->
              <el-form-item label="信用历史" v-for="(m, i) in Moelform.CreditHistory" :key="m.key"
                :prop="Moelform.CreditHistory">
                <div class="modeForm">
                  <div class="el_sel_btn">
                    <ModeSelect v-model="m['CreditHistory']" :ModeData="CreditHistory" :ModeIsDisabled="m.IsDisabled" />
                    &emsp;&emsp;

                    <el-tooltip v-if="!m.IsDisabled" effect="dark" content="添加" placement="top">
                      <el-button @click="handleSelection(m, Number(m.key + 1), 'CreditHistory', CreditHistory)" link
                        class="tran45" type="primary" :icon="useRenderIcon(CloseBold)" /></el-tooltip>
                    <el-tooltip effect="dark" content="删除" placement="top" v-else>
                      <el-button @click="deleteFormValue(m, m.key, 'CreditHistory', CreditHistory)" link type="danger"
                        :icon="useRenderIcon(CloseBold)" />
                    </el-tooltip>
                  </div>
                  <div class="show_view">
                    <div class="show_view_list show_left_bor4">
                      <p class="view_list1">{{ m['CreditHistory']?.lableOne?.label }}</p>
                      <p class="view_list2">{{ m['CreditHistory']?.lableTow?.label }}</p>
                      <div class="show_view_lists">
                        <dl v-for="(ll, ii) in m?.CreditHistory?.lableTow?.children" :key="ii">
                          <dd>{{ ll.text }}</dd>
                          <dd><span>{{ ll.score }}分</span></dd>
                        </dl>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <!-- 人脉关系 -->
              <el-form-item label="人脉关系" v-for="(m, i) in Moelform.InterpersonalRelationship" :key="m.key"
                :prop="Moelform.InterpersonalRelationship">
                <div class="modeForm">
                  <div class="el_sel_btn">
                    <ModeSelect v-model="m['InterpersonalRelationship']" :ModeData="InterpersonalRelationship"
                      :ModeIsDisabled="m.IsDisabled" />
                    &emsp;&emsp;
                    <el-tooltip v-if="!m.IsDisabled" effect="dark" content="添加" placement="top">
                      <el-button
                        @click="handleSelection(m, Number(m.key + 1), 'InterpersonalRelationship', InterpersonalRelationship)"
                        link class="tran45" type="primary" :icon="useRenderIcon(CloseBold)" /></el-tooltip>
                    <el-tooltip effect="dark" content="删除" placement="top" v-else>
                      <el-button
                        @click="deleteFormValue(m, m.key, 'InterpersonalRelationship', InterpersonalRelationship)" link
                        type="danger" :icon="useRenderIcon(CloseBold)" />
                    </el-tooltip>
                  </div>
                  <div class="show_view">
                    <div class="show_view_list show_left_bor5">
                      <p class="view_list1">{{ m['InterpersonalRelationship']?.lableOne?.label }}</p>
                      <p class="view_list2">{{ m['InterpersonalRelationship']?.lableTow?.label }}</p>
                      <div class="show_view_lists">
                        <dl v-for="(ll, ii) in m?.InterpersonalRelationship?.lableTow?.children" :key="ii">
                          <dd>{{ ll.text }}</dd>
                          <dd><span>{{ ll.score }}分</span></dd>
                        </dl>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </TransitionGroup>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button @click="SubimtFrom(RefMoelform)" :loading="btnloading" type="primary">确定</el-button>
        <el-button @click="CloseModeVisible(RefMoelform)"> 取消 </el-button>
      </template>
    </ReDialog>
  </div>
</template>
<script lang="ts" setup>
import qs from 'qs'
import { ref, reactive, nextTick, computed, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import ModeSelect from "./ModeSelect.vue"
import { useRoute } from 'vue-router';
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import CloseBold from "@iconify-icons/ep/close-bold";
import { GetPersonalCreditData, CreatePersonalCreditModel } from "@/api/stu/DataScene";
const emit = defineEmits(['GetMySortsList'])
const route = useRoute()
const ModeVisible = ref<boolean>(false);
const IdentityTrait = ref();
const BehavioralTrait = ref();
const CapacityPerform = ref();
const CreditHistory = ref();
const NAllArrys = ref<any>([]);
const AllArrys = ref<any>([]);
const InterpersonalRelationship = ref();
const RefMoelform = ref<FormInstance>();
const btnloading = ref(false);
// 获取选中的一级value 放进 container
/* 控制添加摁钮 */
/* end 摁钮 */
const Moelform = reactive<any>({
  modeName: "",
  IdentityTrait: [{ key: 1, IsDisabled: false }],
  BehavioralTrait: [{ key: 1, IsDisabled: false }],
  CapacityPerform: [{ key: 1, IsDisabled: false }],
  CreditHistory: [{ key: 1, IsDisabled: false }],
  InterpersonalRelationship: [{ key: 1, IsDisabled: false }],
});

// 选择
function handleSelection(val, nums, property, arr) {
  let arrys = [].concat(...arr.map(q => q.children));
  if (!val[property]) {
    ElMessage.warning("请选择完毕后添加");
    return;
  }
  if (Moelform[property].length == arrys.length) {
    ElMessage.warning(`当前分类最多可添加${arrys.length}条数据`);
    return;
  }

  arr.forEach(obj => {
    obj.children.forEach(child => {
      if (child.label == val[property]?.lableTow?.label) child.IsDisabled = true;
    });
  });

  val.IsDisabled = true;
  const obj = { key: nums, IsDisabled: false };

  // 根据不同的 property 决定将 obj 添加到哪个数组中
  if (property === 'IdentityTrait') {
    Moelform.IdentityTrait.push(obj);
  } else if (property === 'BehavioralTrait') {
    Moelform.BehavioralTrait.push(obj);
  } else if (property === 'CapacityPerform') {
    Moelform.CapacityPerform.push(obj);
  } else if (property === 'CreditHistory') {
    Moelform.CreditHistory.push(obj);
  } else if (property === 'InterpersonalRelationship') {
    Moelform.InterpersonalRelationship.push(obj);
  }
}

function deleteFormValue(value, num, form, data) {
  data.forEach(obj => {
    obj.children.forEach(child => {
      if (child.label == value[form]?.lableTow?.label) child.IsDisabled = false;
    });
  });
  if (Moelform[form].length == 1) return;
  value.IsDisabled = false;
  Moelform[form] = Moelform[form].filter(obj => obj.key !== num);
}


// 提交表单
function SubimtFrom(row) {
  (row as any).validate(async valid => {
    if (!valid) return;
    let Arry_IdentityTrait = [];
    let Arry_CapacityPerform = [];
    let Arry_CreditHistory = [];
    let Arry_InterpersonalRelationship = [];
    let Arry_BehavioralTrait = [];
    let SeleteArry = [];
    const ArryName = ['IdentityTrait', 'CapacityPerform', 'CreditHistory', 'InterpersonalRelationship', 'BehavioralTrait']
    const AllArry = Object.values(Moelform).filter(item => Array.isArray(item))
    AllArry.forEach((item: any) => {
      item.forEach(item2 => {
        for (let key in item2) {
          if (ArryName.includes(key)) {
            SeleteArry.push(item2[key].lableTow)
          }
        }
      })
    })
    function pushToArrayIfPresent(arry, key) { if (key?.lableTow) arry.push(key.lableTow.creditInfoItemId); }


    for (let key in Moelform) {
      if (key == "IdentityTrait") {
        Moelform[key].forEach((el) => {
          for (let keys in el) {
            if (keys.includes("IdentityTrait")) pushToArrayIfPresent(Arry_IdentityTrait, el[keys]);
          }
        })
      }
      if (key == "CapacityPerform") {
        Moelform[key].forEach((el) => {
          for (let keys in el) {
            if (keys.includes("CapacityPerform")) pushToArrayIfPresent(Arry_CapacityPerform, el[keys]);
          }
        })
      }
      if (key == "CreditHistory") {
        Moelform[key].forEach((el) => {
          for (let keys in el) {
            if (keys.includes("CreditHistory")) pushToArrayIfPresent(Arry_CreditHistory, el[keys]);
          }
        })
      }
      if (key == "InterpersonalRelationship") {
        Moelform[key].forEach((el) => {
          for (let keys in el) {
            if (keys.includes("InterpersonalRelationship")) pushToArrayIfPresent(Arry_InterpersonalRelationship, el[keys]);
          }
        })
      }
      if (key == "BehavioralTrait") {
        Moelform[key].forEach((el) => {
          for (let keys in el) {
            if (keys.includes("BehavioralTrait")) pushToArrayIfPresent(Arry_BehavioralTrait, el[keys]);
          }
        })
      }
    }
    // 必填项总长度
    const RequiredLen = NAllArrys.value.filter(item => item.vereist);
    // 已选的
    const SeleteRequiredLen = SeleteArry.filter(item => item && item.vereist);
    if (RequiredLen.length !== SeleteRequiredLen.length) {
      ElMessage.warning("尚有必选项未选，请注意检查");
      return
    }

    // TODO:为避免删除后又选择时数据重复
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      modelName: Moelform.modeName,
      identityTrait: JSON.stringify([...new Set(Arry_IdentityTrait)]),
      capacityPerform: JSON.stringify([...new Set(Arry_CapacityPerform)]),
      creditHistory: JSON.stringify([...new Set(Arry_CreditHistory)]),
      interpersonalRelationship: JSON.stringify([...new Set(Arry_InterpersonalRelationship)]),
      behavioralTrait: JSON.stringify([...new Set(Arry_BehavioralTrait)])
    }
    btnloading.value = true;
    const res = await CreatePersonalCreditModel(data);
    if (res.success) {
      // ModeVisible.value = false;
      // row.resetFields();
      CloseModeVisible(row)
      btnloading.value = false;
      emit("GetMySortsList");
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => {
        btnloading.value = false;
      }, 1500);
    }
  })
}

// 修改对话框状态
function SetModeVisible() {
  GetPersonalCreditDatas()
  ModeVisible.value = true;
}

// 关闭对话框
function CloseModeVisible(row) {
  row.resetFields()
  ModeVisible.value = false;
  Moelform.IdentityTrait = [{ key: 1, IsDisabled: false }]
  Moelform.BehavioralTrait = [{ key: 1, IsDisabled: false }]
  Moelform.CapacityPerform = [{ key: 1, IsDisabled: false }]
  Moelform.CreditHistory = [{ key: 1, IsDisabled: false }]
  Moelform.InterpersonalRelationship = [{ key: 1, IsDisabled: false }]
}


async function GetPersonalCreditDatas() {
  const res = await GetPersonalCreditData();
  IdentityTrait.value = res.data.identityTrait;
  CapacityPerform.value = res.data.capacityPerform;
  CreditHistory.value = res.data.creditHistory;
  InterpersonalRelationship.value = res.data.interpersonalRelationship
  BehavioralTrait.value = res.data.behavioralTrait;
  if (res.success) {
    const arry = [];
    for (let key in res.data) {
      delete res.data['modelName']
      const nk = res.data[key];
      nk.forEach(el => {
        el.children.forEach(els => {
          arry.push(els)
        })
      });
    };
    NAllArrys.value = arry;
  }
}

onMounted(() => { })


defineExpose({
  SetModeVisible,
  CloseModeVisible
})



</script>

<style lang="scss" scoped>
/* 1. 声明过渡效果 */
.fade-move,
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);

}

/* 2. 声明进入和离开的状态 */
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translate(10px, 0);
}

.dialog-footer {
  margin: 0 auto;
  display: block;
  text-align: center;
}

.ModeVisible {
  max-height: 480px;
  overflow-X: hidden;
  overflow-y: auto;
}

.modeForm {
  width: 100%;

  .el_sel_btn {
    width: 100%;
    display: flex;
    align-items: center;

    :deep(.el-icon) {
      font-size: 22px;
    }
  }

  .show_view {
    text-align: left;

    .show_view_list {
      margin-top: 10px;
      padding-left: 10px;

      .view_list2 {
        margin-left: 20px;
      }

      .show_view_lists {
        margin-left: 40px;
      }

      dl {
        display: flex;
        align-items: center;

        dd {
          min-width: 150px;
        }

        span {
          margin-left: 5px;
          color: red;
        }
      }
    }
  }
}

.zhushi {
  text-align: left;
  margin-bottom: 15px;
  padding-left: 17%;
}

.show_left_bor1 {
  border-left: 3px solid #409eff;
}

.show_left_bor2 {
  border-left: 3px solid #bd9b40;
}

.show_left_bor3 {
  border-left: 3px solid #67c23a;
}

.show_left_bor4 {
  border-left: 3px solid #305a91;
}

.show_left_bor5 {
  border-left: 3px solid #913089;
}

.tran45 {
  transform: rotateZ(45deg);
}


@media screen and (max-width:1600px) {
  .ModeVisible {
    max-height: 460px;
  }
}
</style>
